package com.lge.clock.test;

import java.util.Date;

import com.lge.clock.AlarmActivity;

import android.app.Activity;
import android.app.Instrumentation;
import android.app.Instrumentation.ActivityMonitor;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.test.ActivityInstrumentationTestCase2;
import android.test.TouchUtils;
import android.widget.Button;

import com.lge.clock.alarmclock.ALProvider;
import com.lge.clock.alarmclock.AlarmAlert;
import com.lge.clock.alarmclock.Alarms;


public class AlarmAlertActivityTest_checkAlarmInterval extends ActivityInstrumentationTestCase2<AlarmActivity> {

	private Instrumentation inst;
	private ActivityMonitor monitor;
	private Activity currentActivity;

	private TheBroadcastReceiver intentReceiver;	
	private boolean isCalled;	
	Intent fireAlarm;

	public AlarmAlertActivityTest_checkAlarmInterval() {
		// TODO Auto-generated constructor stub
		super("com.lge.clock", AlarmActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		// TODO Auto-generated method stub
		super.setUp();

		inst = getInstrumentation();
		IntentFilter filter1 = null; 
		monitor = inst.addMonitor(filter1, null, false);

		currentActivity = getActivity();

		//setting alarm after 1 minute.
		Date date = new Date();
		int hour = date.getHours();
		int min = date.getMinutes();
		insertTimeToDatabase(hour,min+1);

		//to activate AlarmAlert, renewing the Application
		Intent i = new Intent(currentActivity, AlarmActivity.class);
		currentActivity.startActivity(i);
		inst.waitForIdleSync();
		
		//registering the receiver to catch Alarm Alert Event
		currentActivity = monitor.getLastActivity();
		intentReceiver = new TheBroadcastReceiver();
		IntentFilter filter = new IntentFilter(); 
		filter.addAction(Intent.ACTION_TIME_TICK);	
		currentActivity.registerReceiver(intentReceiver, filter); 		
	}

	@Override
	protected void tearDown() throws Exception {
		// TODO Auto-generated method stub
		currentActivity.unregisterReceiver(intentReceiver);
		clearDatabase();	

		currentActivity.finish();
		super.tearDown();
	}

	
	/**
	 * testAlarmAlertInteral @throws Exception
	 * 1. on Setup(), add 1 alarm which will be alerted after 1 minute.
	 * 2. when ACTION_TIME_TICK is invoked, start to wait 58 seconds.
	 * 3. check whether the activity is AlarmAlert or not.
	 * 4. if the activity is AlarmAlert, start to wait 2 seconds.
	 * 5. check whether the activity is AlarmActivity.
	 * 6. true if the activity is AlarmActivity.
	 */
	public void testAlarmAlertInteral() throws Exception{

		int pastMinutes = 0;

		//waiting at most 60 seconds to start Alerting
		while (true) {
			if (isCalled == true || pastMinutes >= 80) {
				break;
			}

			try {
				Thread.sleep(1000);
				pastMinutes++;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} 

		//checking Alert interval - the status of currentActivivity has to be kept in AlarmAlert during 58 secs
		//when alerting
		pastMinutes = 0;
		while (true) {
			if (pastMinutes >= 58) {
				break;
			}

			try {
				Thread.sleep(1000);
				pastMinutes++;
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} 
		currentActivity = monitor.getLastActivity(); // currentActivity maybe be AlarmAlert
		assertEquals(AlarmAlert.class.getName(), currentActivity.getClass().getName());
		
		//checking Alert interval - the status of currentActivivity has to be kept in AlarmAlert during 58 secs
		//after finishing to alert
		pastMinutes = 0;
		while (true) {
			if (pastMinutes >= 2) {
				break;
			}

			try {
				Thread.sleep(1000);
				pastMinutes++;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		currentActivity = monitor.getLastActivity(); // currentActivity maybe be AlarmActivity 
		assertEquals(AlarmActivity.class.getName(), currentActivity.getClass().getName());
	}

	public void clickButtonById(int id) {
		Button button = (Button)currentActivity.findViewById(id);
		TouchUtils.clickView(this, button);
		inst.waitForIdleSync();
	}
	
	protected void clearDatabase() {
		ContentResolver cr = currentActivity.getContentResolver();

		Cursor c;
		c = cr.query(ALProvider.CONTENT_ALARMS_URI, null, null, null, null);

		if (c.moveToFirst()) {
			cr.delete(ALProvider.CONTENT_ALARMS_URI, null, null);
		}

		c = cr.query(ALProvider.CONTENT_CALCU_URI, null, null, null, null);

		if (c.moveToFirst()) {
			cr.delete(ALProvider.CONTENT_CALCU_URI, null, null);
		}
	}

	public void insertTimeToDatabase(int mHour,int mMinute) {
		ContentResolver cr = currentActivity.getContentResolver();

		int mDayOfWeek = 0;

		ContentValues cv = new ContentValues();
		cv.put("hour",          mHour);
		cv.put("minutes",               mMinute);     
		cv.put("daysofweek",   mDayOfWeek);
		cv.put("enabled",           "1"); 
		cv.put("stop",              ""); 

		ContentValues value = new ContentValues();
		value.put("hour",               mHour);
		value.put("minutes",            mMinute);     
		value.put("daysofweek",   mDayOfWeek);
		value.put("snooze",0);
		value.put("tone", "Off" );
		value.put("vib",       "On");
		value.put("puzzle",    "Off");
		value.put("enabled",        "1" );         
		value.put("widget_yn",  "N" );
		cr.insert(ALProvider.CONTENT_ALARMS_URI,        value); 

		int maxID = 0;

		String[] projection = new String[] { "max(_id) ID" };
		Cursor cc = null;
		try {
			cc = cr.query(Uri.parse(Alarms.CONTENT_ALARMS_URI_STRING.concat("?queryType=1")), projection, null, null, null);
			if (cc != null) {   //WBT fix td 207876
				if (cc.moveToFirst()) {  
					maxID = cc.getInt(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if ( cc != null )
				cc.close();
		}

		cv.put( "aid",    maxID);
		cv.put( "aindex", 0);
		cv.put( "status", "A");
		cr.insert(ALProvider.CONTENT_CALCU_URI, cv);
	}	

	public class TheBroadcastReceiver extends BroadcastReceiver { 

		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
				int id = intent.getIntExtra("id", 0);
				long rTime = intent.getLongExtra("time", 0); 

				//////////////////////////////////////////////////////////////////////
				String  memo  = intent.getStringExtra("memo"); 
				String  gubun  = intent.getStringExtra("gubun"); 
				String	tone  = intent.getStringExtra("tone");
				String	vib   = intent.getStringExtra("vib");    
				String	puzzle   = intent.getStringExtra("puzzle");
				//String  stopflag  = intent.getStringExtra("stop");
				int	snooze    = intent.getIntExtra("snooze", 5);
				//////////////////////////////////////////////////////////////////////	

				fireAlarm = new Intent(currentActivity, AlarmAlert.class); 
				fireAlarm.putExtra("id", id);
				fireAlarm.putExtra("memo", memo);      

				fireAlarm.putExtra("puzzle", puzzle);
				fireAlarm.putExtra("time", 	 rTime); 
				fireAlarm.putExtra("snooze", snooze); 
				fireAlarm.putExtra("tone", tone); 
				fireAlarm.putExtra("vib", vib);              
				fireAlarm.putExtra("stop", intent.getStringExtra("stop") ); 
				fireAlarm.putExtra("gubun",  gubun);    
				fireAlarm.putExtra("multi", intent.getStringExtra("multi") );     
				fireAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); 

				isCalled = true;
			}
		}
	}
} 